<?php

/**
 * Description of Promotion
 *
 * @author Administrator
 */
class Promotion extends CI_Controller {

  protected $class;
  protected $model;

  public function __construct() {
    parent::__construct();
    if (!userdata('username')) {
      redirect('admin/login');
    }
    $this->class = $this->router->fetch_class();
    $model_name = $this->class . "_model";
    $this->model = new $model_name();
    set_userdata('currentURL', current_url());
  }

  protected function _list_data() {
    return array('categories' => $this->category_model->get_all_tree());
  }

  public function index($type = 'all', $max = '', $offset = '') {
    $offset = $offset + 0;
    $max = $this->setting_model->item('max_record');
    if ($type == 'hight_download') {
      $promotions = $this->promotion_download_model->list_download_promotion($max, $offset);
      $total = $this->promotion_download_model->total_download_promotion();
    } else if ($type == 'hight_view') {
      $promotions = $this->promotion_view_model->list_view_promotion($max, $offset);
      $total = $this->promotion_view_model->total_view_promotion();
    } else if ($type == 'hight_rate') {
      $promotions = $this->promotion_rating_model->list_rate_promotion($max, $offset);
      $total = $this->promotion_rating_model->total_rate_promotion();
    } else {
      $total = $this->model->count();
      $promotions = $this->model->get_all(null, null, null, null, null, null, null, null, null, null, null, null, array('date_create' => 'desc'), $max, $offset);
    }
    $this->load->helper('paging');
    $paging = paging('admin/' . $this->class . '/index', $total, $max, $offset, $type);
    $this->load->view('admin/' . $this->class . '/list', array_merge($this->_list_data(), array(
                'objects' => $promotions,
                'total' => $total, 'offset' => $offset, 'max' => $max, 'paging' => $paging)));
  }

  public function list_by_provider($provider_id = 0, $max = '', $offset = '') {
    $offset = $offset + 0;
    $max = $this->setting_model->item('max_record');
    $condition = empty($provider_id) ? null : array('provider_user_id' => $provider_id);
    $total = $this->model->count($condition);
    $this->load->helper('paging');
    $paging = paging('admin/' . $this->class . '/list_by_provider', $total, $max, $offset, $provider_id);
    $this->load->view('admin/' . $this->class . '/provider', array_merge($this->_list_data(), array(
                'objects' => $this->model->get_all($condition, null, null, null, null, null, null, null, null, null, null, null, null, $max, $offset),
                'total' => $total, 'offset' => $offset, 'max' => $max, 'paging' => $paging)));
  }

  public function show($id = '', $tag = 'detail') {
    if (!empty($id)) {
      $obj = $this->model->get($id);
      if (!empty($obj)) {
        $relate_promotions = $this->promotion_relate_model->get_all(null, array('promotion1_id' => $id, 'promotion2_id' => $id));
        $media_promotions = $this->promotion_media_model->get_all(array('promotion_id' => $id));
        $obj['views'] = $this->promotion_view_model->count(array('promotion_id' => $id));
        $obj['downloads'] = $this->promotion_download_model->count(array('promotion_id' => $id));
        $obj['rating'] = $this->promotion_rating_model->count(array('promotion_id' => $id));
        $this->load->view('admin/' . $this->class . '/show', array(
            'obj' => $obj, 'tag' => $tag,
            'relate_promotions' => $relate_promotions,
            'media_promotions' => $media_promotions));
        return;
      }
    }
    set_flash_error($this->lang->line('error.not.found', array($this->lang->line('label.' . $this->class), $id)));
    redirect('admin/' . $this->class);
  }

  public function create($provider_id = 0) {
    $this->load->view('admin/' . $this->class . '/create', array(
        'category' => array(), 'provider_id' => $provider_id));
  }

  private function _save_category($promotion_id, $cat_id) {
    $cat = $this->category_model->get($cat_id);
    if (!empty($cat)) {
      $category = array('cat_id' => $cat_id, 'promotion_id' => $promotion_id, 'date_create' => time());
      $this->category_promotion_model->save($category);
      if(!empty($cat['parent_id'])){
        $this->_save_category($promotion_id, $cat['parent_id']);
      }
    }
  }

  public function save($provider_id = 0) {
    $object = $_REQUEST;
    $object['date_create'] = $object['date_update'] = time();
    $object['remain'] = isset($object['max_download']) ? $object['max_download'] : 0;
    $object['start_date'] = empty($object['start_date']) ? '' : strtotime($object['start_date']);
    $object['end_date'] = empty($object['end_date']) ? '' : strtotime($object['end_date']);
    if (isset($object['status']) && $object['status'] == PROMOTION_PUBLISH) {
      $object['date_publish'] = time();
    }
    $id = $this->model->save($object);
    if (is_array($id))
      set_flash_error($id);
    else
    if (!empty($id)) {
      if (!empty($_REQUEST['category'])) {
        $categories = is_array($_REQUEST['category']) ? $_REQUEST['category'] : array($_REQUEST['category']);
        foreach ($categories as $category) {
          $this->_save_category($id, $category);
        }
      }
      @mkdir($this->setting_model->item('upload_path') . 'promotion');
      @mkdir($this->setting_model->item('upload_path') . 'promotion/' . $id);
      set_flash_message($this->lang->line('message.created', array($this->lang->line('label.' . $this->class), $id)));
      redirect('admin/promotion_relate/create/' . $id);
      return;
    }
    $obj['start_date'] = empty($obj['start_date']) ? '' : date($this->setting_model->item('date_format'), $obj["start_date"]);
    $obj['end_date'] = empty($obj['end_date']) ? '' : date($this->setting_model->item('date_format'), $obj["end_date"]);
    set_flash_error($this->lang->line('error.faltal.error'));
    $this->load->view('admin/' . $this->class . '/create', array(
        'provider_id' => $provider_id, 'obj' => $_REQUEST,
        'category' => empty($_REQUEST['category']) ? array() : $_REQUEST['category']));
  }

  public function edit($id = '', $provider_id = 0) {
    if (!empty($id)) {
      $obj = $this->model->get($id);
      if (!empty($obj)) {
        $temp = array();
        $category = $this->category_promotion_model->get_all(array('promotion_id' => $id));
        foreach ($category as $cat) {
          $temp[] = $cat['cat_id'];
        }
        $obj['start_date'] = empty($obj['start_date']) ? '' : date($this->setting_model->item('date_format'), $obj["start_date"]);
        $obj['end_date'] = empty($obj['end_date']) ? '' : date($this->setting_model->item('date_format'), $obj["end_date"]);
        $this->load->view('admin/' . $this->class . '/edit', array(
            'provider_id' => $provider_id,
            'obj' => $obj, 'category' => $temp));
        return;
      }
    }
    set_flash_error($this->lang->line('error.not.found', array($this->lang->line('label.' . $this->class), $id)));
    redirect('admin/' . $this->class);
  }

  public function update($provider_id = 0) {
    $object = $_REQUEST;
    $object['start_date'] = empty($object['start_date']) ? '' : strtotime($object['start_date']);
    $object['end_date'] = empty($object['end_date']) ? '' : strtotime($object['end_date']);
    if (isset($object['status']) && $object['status'] == PROMOTION_PUBLISH) {
      $object['date_publish'] = time();
    }
    $id = $this->model->save($object);
    if (is_array($id))
      set_flash_error($id);
    else
    if ($id === true) {
      $this->category_promotion_model->delete(array('promotion_id' => $_REQUEST['id']));
      if (!empty($_REQUEST['category'])) {
        $categories = is_array($_REQUEST['category']) ? $_REQUEST['category'] : array($_REQUEST['category']);
        foreach ($categories as $category) {
          $this->_save_category($object['id'], $category);
        }
      }
      set_flash_message($this->lang->line('message.updated', array($this->lang->line('label.' . $this->class), $_REQUEST['id'])));
      redirect('admin/promotion/show/' . $_REQUEST['id'] . '/relate');
      return;
    } else
      set_flash_error($this->lang->line('error.faltal.error'));
    $this->load->view('admin/' . $this->class . '/edit', array(
        'provider_id' => $provider_id, 'obj' => $_REQUEST,
        'category' => empty($_REQUEST['category']) ? array() : $_REQUEST['category']));
  }

  protected function _delete($id) {
    @deletedir($this->setting_model->item('upload_path') . 'promotion/' . $id);
    $this->promotion_media_model->delete(array('promotion_id' => $id));
    $this->promotion_download_model->delete(array('promotion_id' => $id));
    $this->promotion_view_model->delete(array('promotion_id' => $id));
    $this->category_promotion_model->delete(array('promotion_id' => $id));
    $this->discussion_model->delete(array('promotion_id' => $id));
    $this->promotion_favorite_model->delete(array('promotion_id' => $id));
    $this->promotion_relate_model->delete(null, array('promotion1_id' => $id), array('promotion2_id' => $id));
  }

  public function delete($id = '') {
    if (!empty($id)) {
      $obj = $this->model->get($id);
      if (!empty($obj)) {
        $this->_delete($id);
        $this->model->delete($id);
        set_flash_message($this->lang->line('message.deleted', array($this->lang->line('label.' . $this->class), $id)));
        redirect('admin/' . $this->class);
        return;
      }
    }
    set_flash_error($this->lang->line('error.not.found', array($this->lang->line('label.' . $this->class), $id)));
    redirect('admin/' . $this->class);
  }

  public function action() {
    if (!empty($_REQUEST['btnAction']) && !empty($_REQUEST['action_to'])) {
      $action_to = $_REQUEST['action_to'];
      $action_to = is_array($action_to) ? $action_to : array($action_to);
      foreach ($action_to as $id) {
        if ($_REQUEST['btnAction'] == 'delete') {
          $this->_delete($id);
          $this->model->delete(array('id' => $id));
        } else {
          $object = $this->model->get($id);
          if (!empty($object)) {
            if ($_REQUEST['btnAction'] == 'approve') {
              $object['status'] = PROMOTION_APPROVED;
            } else if ($_REQUEST['btnAction'] == 'publish') {
              $object['status'] = PROMOTION_PUBLISH;
            } else if ($_REQUEST['btnAction'] == 'reject') {
              $object['status'] = PROMOTION_REJECT;
            } else if ($_REQUEST['btnAction'] == 'block') {
              $object['status'] = PROMOTION_BLOCK;
            }
            $this->model->save($object);
          }
        }
      }
      set_flash_message($this->lang->line('message.action.success'));
    } else
      set_flash_error($this->lang->line('error.action.no.select'));
    redirect('admin/' . $this->class);
  }

  public function approve($id = '') {
    if (!empty($id)) {
      $obj = $this->model->get($id);
      if (!empty($obj)) {
        $obj['status'] = PROMOTION_APPROVED;
        $result = $this->model->save($obj);
        if ($result == true) {
          set_flash_message($this->lang->line('message.approved', array($this->lang->line('label.' . $this->class), $id)));
        } else {
          set_flash_error($this->lang->line('error.faltal.error'));
        }
        redirect('admin/' . $this->class . '/show/' . $id);
        return;
      }
    }
    set_flash_error($this->lang->line('error.not.found', array($this->lang->line('label.' . $this->class), $id)));
    redirect('admin/' . $this->class);
  }

  public function publish($id = '') {
    if (!empty($id)) {
      $obj = $this->model->get($id);
      if (!empty($obj)) {
        $obj['status'] = PROMOTION_PUBLISH;
        $obj['date_publish'] = time();
        $result = $this->model->save($obj);
        if ($result == true) {
          set_flash_message($this->lang->line('message.published', array($this->lang->line('label.' . $this->class), $id)));
        } else {
          set_flash_error($this->lang->line('error.faltal.error'));
        }
        redirect('admin/' . $this->class . '/show/' . $id);
        return;
      }
    }
    set_flash_error($this->lang->line('error.not.found', array($this->lang->line('label.' . $this->class), $id)));
    redirect('admin/' . $this->class);
  }

  public function reject($id = '') {
    if (!empty($id)) {
      $obj = $this->model->get($id);
      if (!empty($obj)) {
        $obj['status'] = PROMOTION_REJECT;
        $result = $this->model->save($obj);
        if ($result == true) {
          set_flash_message($this->lang->line('message.rejected', array($this->lang->line('label.' . $this->class), $id)));
        } else {
          set_flash_error($this->lang->line('error.faltal.error'));
        }
        redirect('admin/' . $this->class . '/show/' . $id);
        return;
      }
    }
    set_flash_error($this->lang->line('error.not.found', array($this->lang->line('label.' . $this->class), $id)));
    redirect('admin/' . $this->class);
  }

  public function block($id = '') {
    if (!empty($id)) {
      $obj = $this->model->get($id);
      if (!empty($obj)) {
        $obj['status'] = PROMOTION_BLOCK;
        $result = $this->model->save($obj);
        if ($result == true) {
          set_flash_message($this->lang->line('message.blocked', array($this->lang->line('label.' . $this->class), $id)));
        } else {
          set_flash_error($this->lang->line('error.faltal.error'));
        }
        redirect('admin/' . $this->class . '/show/' . $id);
        return;
      }
    }
    set_flash_error($this->lang->line('error.not.found', array($this->lang->line('label.' . $this->class), $id)));
    redirect('admin/' . $this->class);
  }

  public function search($max = '', $offset = '') {
    $offset = $offset + 0;
    $conditions = array('status' => empty($_REQUEST['status']) ? '' : $_REQUEST['status'],
        'category_id' => empty($_REQUEST['category_id']) ? '' : $_REQUEST['category_id']);
    $in_list = array();
    $params = array();
    foreach ($conditions as $field => $value) {
      if ($value == 'all') {
        unset($conditions[$field]);
        continue;
      }
      $params[] = $field . '=' . $value;
    }
    if (!empty($conditions['category_id'])) {
      $category = $this->category_promotion_model->get_all(array('cat_id' => $conditions['category_id']));
      $in_list['id'] = array(0);
      foreach ($category as $cat) {
        $in_list['id'][] = $cat['promotion_id'];
      }
    }
    unset($conditions['category_id']);
    $params = '?' . implode('&', $params);
    $total = $this->model->count($conditions, null, $in_list);
    $max = $this->setting_model->item('max_record');
    $this->load->helper('paging');
    $paging = paging('admin/' . $this->class . '/search', $total, $max, $offset, array(), $params);

    $this->load->view('admin/' . $this->class . '/list', array_merge($_REQUEST, $this->_list_data(), array(
                'objects' => $this->model->get_all($conditions, null, $in_list, null, null, null, null, null, null, null, null, null, null, $max, $offset),
                'total' => $total, 'offset' => $offset, 'max' => $max, 'paging' => $paging)));
  }

  public function test_post_fb() {

    $fbconfig = array();
    $fbconfig['appid'] = "289823484465602";
    $fbconfig['secret'] = "2660af84e6211ceb91cf13e74cff45c4";
    $fbconfig['pageid'] = "493195957358751";
    $token_url1 = file_get_contents("https://graph.facebook.com/oauth/access_token?client_id=" .
            $fbconfig['appid'] . "&client_secret=" . $fbconfig['secret'] . "&grant_type=client_credentials");
    $token_url1 = explode('=', $token_url1);
    $token_url1 = $token_url1[1];
    echo $token_url1;
    $attachment = array(
        'access_token' => $token_url1,
        'name' => 'test feed',
        'link' => site_url(''),
        'description' => 'test feed'
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/' . $fbconfig['pageid'] . '/feed');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $attachment);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  //to suppress the curl output 
    $result = curl_exec($ch);
    var_dump($result);
    curl_close($ch);
  }

}